package com.business_clean.ui.activity.attendance;

import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.business_clean.R;
import com.business_clean.app.App;
import com.business_clean.app.base.BaseActivity;
import com.business_clean.app.ext.CommonUtils;
import com.business_clean.app.uitl.ToastUtil;
import com.business_clean.app.weight.dialog.CustomImageViewPagerPopup;
import com.business_clean.data.initconfig.MenuEntity;
import com.business_clean.data.mode.ImageEntity;
import com.business_clean.data.mode.attendance.MyAttendanceDetailClockEntity;
import com.business_clean.data.mode.attendance.MyAttendanceDetailEntity;
import com.business_clean.data.mode.attendance.MyAttendanceEntity;
import com.business_clean.data.mode.attendance.MyAttendanceItemEntity;
import com.business_clean.databinding.ActivityMyAttendanceBinding;
import com.business_clean.ui.adapter.BaseMenuAdapter;
import com.business_clean.ui.adapter.attendance.MyAttendanceAdapter;
import com.business_clean.viewmodel.request.AttendanceViewModel;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarView;
import com.luck.picture.lib.decoration.MyGridSpacingItemDecoration;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;

import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.hgj.mvvmhelper.ext.LogExtKt;

public class MyAttendanceActivity extends BaseActivity<AttendanceViewModel, ActivityMyAttendanceBinding> {


    private String uuid;
    private String stat_month = "";

    private BaseMenuAdapter menuAdapter;

    private MyAttendanceAdapter mAdapter;


    private String stat_uuid;

    private boolean isWorkOverTime = false;


    @Override
    public void initView(@Nullable Bundle savedInstanceState) {
        if (getIntent() != null && getIntent().getExtras() != null) {
            uuid = getIntent().getExtras().getString("uuid");
        }

        mAdapter = new MyAttendanceAdapter();
        menuAdapter = new BaseMenuAdapter();

//        setAdapterEmpty(null);

//        View headerView = getLayoutInflater().inflate(R.layout.header_my_attendance, null);
//        headerMyAttendanceBinding = DataBindingUtil.bind(headerView);
//        mAdapter.setHeaderView(headerView);

        mDatabind.header.tvDate.setText(mDatabind.header.calendarView.getCurYear() + "-" +
                formatNumberWithZero(mDatabind.header.calendarView.getCurMonth()));

        mDatabind.header.recyclerStat.setAdapter(menuAdapter);
        mDatabind.header.recyclerStat.setLayoutManager(new GridLayoutManager(this, 5));
        mDatabind.header.recyclerStat.addItemDecoration(new MyGridSpacingItemDecoration(5, SizeUtils.dp2px(10), true));

        mDatabind.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mDatabind.recyclerView.setAdapter(mAdapter);

        getAttendanceStat(null);
        requestOne();
    }

    public String formatNumberWithZero(int number) {
        if (number < 10) {
            return "0" + number;
        } else {
            return String.valueOf(number);
        }
    }

    private void requestDetail(String stat_uuid) {
        mViewModel.requestMyAttendanceToday(stat_uuid);
    }

    private void requestOne() {
        HashMap<String, String> hashMap = new HashMap<>();
        stat_month = mDatabind.header.tvDate.getText().toString();
        hashMap.put("stat_month", "" + stat_month);
        if (!TextUtils.isEmpty(uuid)) {
            hashMap.put("uuid", uuid);
        } else {
            hashMap.put("uuid", "" + App.appViewModelInstance.getUserInfo().getValue().getUser().getUuid());
        }
        mViewModel.requestMyAttendance(hashMap);
    }

    @Override
    public void onBindViewClick() {
        //上个月
        mDatabind.header.tvLeftChange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDatabind.header.calendarView.scrollToNext();
            }
        });
        //下个月
        mDatabind.header.tvRightChange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDatabind.header.calendarView.scrollToPre();
            }
        });
        //修正数据
        mAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                switch (view.getId()) {
                    case R.id.iv_item_my_attendance_action://上班
                        ImageView inImage = view.findViewById(R.id.iv_item_my_attendance_action);
                        showPreViewImage(inImage, mAdapter.getData().get(position).getIn_class_info().getClock_info());
                        break;
                    case R.id.iv_item_my_attendance_off_work_action://下班
                        ImageView inImageOffWork = view.findViewById(R.id.iv_item_my_attendance_action);
                        showPreViewImage(inImageOffWork, mAdapter.getData().get(position).getOut_class_info().getClock_info());
                        break;
                    case R.id.tv_item_classes_update:
                        String[] strings = {"改为休假", "改为正常出勤", "改为旷工", "改为休息", "改为加班"};
                        if (isWorkOverTime) {
                            strings[4] = "取消加班";
                        } else {
                            strings[4] = "改为加班";
                        }
                        CommonUtils.showBottomListWith(MyAttendanceActivity.this, 20, "请选择出勤情况", strings, new OnSelectListener() {
                            @Override
                            public void onSelect(int position, String text) {
                                String status = "";
                                switch (position) {
                                    case 0:
                                        status = "1";
                                        break;
                                    case 1:
                                        status = "2";
                                        break;
                                    case 2:
                                        status = "4";
                                        break;
                                    case 3:
                                        status = "5";
                                        break;
                                    case 4:
                                        if (isWorkOverTime) {
                                            status = "20";
                                        } else {
                                            status = "6";
                                        }
                                        break;
                                }
                                HashMap<String, String> hashMap = new HashMap<>();
                                hashMap.put("stat_uuid", "" + stat_uuid);
                                hashMap.put("status", status);
                                mViewModel.updateAttendanceStatus(hashMap);
                            }
                        });
                        break;
                }
            }
        });
//        mDatabind.header.tvClassesUpdate.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                String[] strings = {"改为休假", "改为正常出勤", "改为旷工", "改为休息", "改为加班"};
//                if (isWorkOverTime) {
//                    strings[4] = "取消加班";
//                } else {
//                    strings[4] = "改为加班";
//                }
//                CommonUtils.showBottomListWith(MyAttendanceActivity.this, 20, "请选择出勤情况", strings, new OnSelectListener() {
//                    @Override
//                    public void onSelect(int position, String text) {
//                        String status = "";
//                        switch (position) {
//                            case 0:
//                                status = "1";
//                                break;
//                            case 1:
//                                status = "2";
//                                break;
//                            case 2:
//                                status = "4";
//                                break;
//                            case 3:
//                                status = "5";
//                                break;
//                            case 4:
//                                if (isWorkOverTime) {
//                                    status = "20";
//                                } else {
//                                    status = "6";
//                                }
//                                break;
//                        }
//                        HashMap<String, String> hashMap = new HashMap<>();
//                        hashMap.put("stat_uuid", "" + stat_uuid);
//                        hashMap.put("status", status);
//                        mViewModel.updateAttendanceStatus(hashMap);
//                    }
//                });
//            }
//        });
    }

    /**
     * 做转换 需要去公共图片查看的地方
     *
     * @param imageView
     */
    private void showPreViewImage(ImageView imageView, MyAttendanceDetailClockEntity clock) {
        List<ImageEntity> images = new ArrayList<>();
        ImageEntity image = new ImageEntity();
        image.setResouceType(Integer.parseInt(clock.getMedia_type()));//数据类型
        if ("2".equals(clock.getMedia_type())) {
            image.setVideoUrl(clock.getMedia_url());
            image.setVideoCoverUrl(clock.getPic_thumb());
        } else {
            image.setPhotoUrl(clock.getMedia_url());
            image.setOriginalUrl(clock.getOrigin_media_url());
        }
        images.add(image);
        new XPopup.Builder(this)
                .asCustom(new CustomImageViewPagerPopup(this, images, 0))
                .show();
    }


    @Override
    public void initObserver() {
        mDatabind.header.calendarView.setOnCalendarSelectListener(new CalendarView.OnCalendarSelectListener() {
            @Override
            public void onCalendarOutOfRange(Calendar calendar) {

            }

            @Override
            public void onCalendarSelect(Calendar calendar, boolean isClick) {
                LogExtKt.logE("点击了，日历" + calendar.getMonth() + " - " + calendar.getDay() + " - scheme -> " + calendar.getScheme(), "");
                mDatabind.header.tvDate.setText(calendar.getYear() + "-" + formatNumberWithZero(calendar.getMonth()));
                if (!TextUtils.isEmpty(calendar.getScheme())) {
                    if (calendar.getSchemes().contains("加班")) {//查询是否有加班的
                        isWorkOverTime = true;
                    }
                    stat_uuid = calendar.getScheme();
                    requestDetail(calendar.getScheme());
                } else {
                    isWorkOverTime = false;
                    ToastUtil.show("暂无考勤数据");
                    mAdapter.setList(null);
                    mDatabind.recyclerView.setVisibility(View.GONE);
                    mDatabind.llEmpty.setVisibility(View.VISIBLE);
                    mDatabind.tvEmptyData.setText("暂无考勤数据");
                }
            }
        });
    }

    @Override
    public void onRequestSuccess() {
        mViewModel.getMyAttendanceEntity().observe(this, new Observer<MyAttendanceEntity>() {
            @Override
            public void onChanged(MyAttendanceEntity myAttendanceEntity) {
//                mDatabind.list.refreshLayout.finishRefresh();
                if (myAttendanceEntity != null) {
                    if (!TextUtils.isEmpty(uuid)) {
                        mDatabind.tabbar.setTitle(myAttendanceEntity.getUser_name() + "的考勤统计");
                    }
                    getAttendanceStat(myAttendanceEntity);
                    Map<String, Calendar> map = new HashMap<>();
                    //日历绘制
                    for (int i = 0; i < myAttendanceEntity.getList().size(); i++) {
                        MyAttendanceItemEntity data = myAttendanceEntity.getList().get(i);
                        String year = data.getAttendance_year();
                        String month = data.getAttendance_month();
                        String day = data.getAttendance_day();
                        if (!TextUtils.isEmpty(year) && !TextUtils.isEmpty(month) && !TextUtils.isEmpty(day)) {
                            //根据状态，给日历，增加状态
                            map.put(getSchemeCalendar(Integer.parseInt(year), Integer.parseInt(month), Integer.parseInt(day), 0xFF40db25,
                                            data.getStat_uuid(), data.getIs_attendance(), data.getIs_actual_attendance(), data.getIs_holiday(),
                                            data.getIs_absenteeism(), data.getIs_qk(), data.getIs_overtime(), data.getIs_entry(), data.getIs_left()
                                    ).toString(),
                                    getSchemeCalendar(Integer.parseInt(year), Integer.parseInt(month), Integer.parseInt(day), 0xFF40db25,
                                            data.getStat_uuid(), data.getIs_attendance(), data.getIs_actual_attendance(), data.getIs_holiday(),
                                            data.getIs_absenteeism(), data.getIs_qk(), data.getIs_overtime(), data.getIs_entry(), data.getIs_left()
                                    ));
                        }
                    }
                    mDatabind.header.calendarView.setSchemeDate(map);

                    //获取到当前的统计Id 去获取详情
                    for (int j = 0; j < myAttendanceEntity.getList().size(); j++) {
                        MyAttendanceItemEntity data = myAttendanceEntity.getList().get(j);

                        if (mDatabind.header.calendarView.getCurYear() == Integer.parseInt(data.getAttendance_year()) &&
                                mDatabind.header.calendarView.getCurMonth() == Integer.parseInt(data.getAttendance_month()) &&
                                mDatabind.header.calendarView.getCurDay() == Integer.parseInt(data.getAttendance_day())) {
                            LogUtils.e("有对应的 uuid " + data.getStat_uuid());
                            requestDetail(data.getStat_uuid());
                            break;
                        }
                    }
                }
            }
        });

        mViewModel.getDetailEntity().observe(this, new Observer<MyAttendanceDetailEntity>() {
            @Override
            public void onChanged(MyAttendanceDetailEntity myAttendanceDetailEntity) {
                if (myAttendanceDetailEntity != null) {
//                mDatabind.header.tvClassesName.setText(myAttendanceDetailEntity.getClass_name());
                    //如果有班次的话，说明是需要考勤的
                    if (!TextUtils.isEmpty(myAttendanceDetailEntity.getClass_name())) {
                        mDatabind.recyclerView.setVisibility(View.VISIBLE);
                        mDatabind.llEmpty.setVisibility(View.GONE);
                        mAdapter.updateClassesName(myAttendanceDetailEntity.getClass_name());
                        mAdapter.setList(myAttendanceDetailEntity.getList());
                    } else {//负责就是无需考勤，现实无需考勤的界面
                        mDatabind.recyclerView.setVisibility(View.GONE);
                        mDatabind.llEmpty.setVisibility(View.VISIBLE);
                        mDatabind.tvEmptyData.setText("无需考勤");
                    }
                }

            }
        });


        //修正后更新界面的数据
        mViewModel.getUpdateAttendance().observe(this, new Observer<Object>() {
            @Override
            public void onChanged(Object o) {
                requestOne();
            }
        });
    }


    private Calendar getSchemeCalendar(int year, int month, int day, int color, String text,
                                       String is_attendance, String is_actual_attendance, String is_holiday,
                                       String is_absenteeism, String is_qk, String is_overtime, String is_entry, String is_left) {
        Calendar calendar = new Calendar();
        calendar.setYear(year);
        calendar.setMonth(month);
        calendar.setDay(day);
        calendar.setSchemeColor(color);//如果单独标记颜色、则会使用这个颜色
        calendar.setScheme(text);

        if ("2".equals(is_attendance) && "2".equals(is_absenteeism) && "2".equals(is_qk)) {//是否休息
            calendar.addScheme(Color.parseColor("#000000"), "休息");
        }
        if ("1".equals(is_actual_attendance)) {//是否实际出勤 1是2否
            calendar.addScheme(Color.parseColor("#09BE89"), "出勤");
        }
        if ("1".equals(is_holiday)) {//是否假期 1是2否
            calendar.addScheme(Color.parseColor("#A671CF"), "休假");
        }
        if ("1".equals(is_absenteeism)) {//是否旷工 1是2否
            calendar.addScheme(Color.parseColor("#FF4040"), "旷工");
        }
        if ("1".equals(is_qk)) {//是否缺卡 1是2否
            calendar.addScheme(Color.parseColor("#FF801A"), "缺卡");
        }
        if ("1".equals(is_overtime)) {///是否加班 1是2否
            calendar.addScheme(Color.parseColor("#1890FF"), "加班");
        }
        if ("1".equals(is_entry)) {///是否入职 1是2否
            calendar.addScheme(Color.parseColor("#1890FF"), "入职");
        }
        if ("1".equals(is_left)) {///是否离职 1是2否
            calendar.addScheme(Color.parseColor("#1890FF"), "离职");
        }
        return calendar;
    }

    private void setAdapterEmpty(String text) {
        View empty = View.inflate(this, R.layout.layout_empty, null);
        TextView tvEmpty = empty.findViewById(R.id.tv_empty_data);
        if (!TextUtils.isEmpty(text)) {
            tvEmpty.setText(text);
        } else {
            tvEmpty.setText("暂无考勤数据");
        }
        mAdapter.setEmptyView(empty);
    }

    private void getAttendanceStat(MyAttendanceEntity data) {
        List<MenuEntity> attenDances = new ArrayList<>();
        if (data != null) {
            attenDances.add(new MenuEntity("" + data.getAttendance_days(), "天", "应出勤", "#000000"));
            attenDances.add(new MenuEntity("" + data.getActual_attendance_days(), "天", "实出勤", "#09BE89"));
            attenDances.add(new MenuEntity("" + data.getRest_days(), "天", "休息", "#000000"));
            attenDances.add(new MenuEntity("" + data.getHoliday_days(), "天", "休假", "#A671CF"));
            attenDances.add(new MenuEntity("" + data.getOvertime_days(), "天", "加班", "#1890FF"));
            attenDances.add(new MenuEntity("" + data.getAbsenteeism_days(), "天", "旷工", "#FF4040"));
            attenDances.add(new MenuEntity("" + data.getQk_days(), "次", "缺卡", "#FF801A"));
        } else {
            attenDances.add(new MenuEntity("0", "天", "应出勤", "#000000"));
            attenDances.add(new MenuEntity("0", "天", "实出勤", "#09BE89"));
            attenDances.add(new MenuEntity("0", "天", "休息", "#000000"));
            attenDances.add(new MenuEntity("0", "天", "休假", "#A671CF"));
            attenDances.add(new MenuEntity("0", "天", "加班", "#1890FF"));
            attenDances.add(new MenuEntity("0", "天", "旷工", "#FF4040"));
            attenDances.add(new MenuEntity("0", "次", "缺卡", "#FF801A"));
        }
        menuAdapter.setList(attenDances);
    }
}